package controller;

import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import model.ListItem;

public class FileManager {
	public static void saveToFile(Object o, String filename)
	{
		try 
		{
			ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filename)); 
			
			if (o instanceof ObservableList)
			{
				ObservableList ol = (ObservableList) o;
				
				os.writeObject("ObservableList");
				
				for (Object i : ol)
					os.writeObject(i);
			}
			else
			{
				os.writeObject("Serializable");
				os.writeObject(o);
			}

			os.flush();
			os.close();
		} 
		catch (Exception e1) 
		{
			throw new RuntimeException(e1);
		}
	}
	
	public static Object loadFromFile(String filename)
	{
		try 
		{
			ObjectInputStream is = new ObjectInputStream(new FileInputStream(filename)); 
			
			String h = (String) is.readObject();
			
			if (h.equals("ObservableList"))
			{
				ObservableList<ListItem> l = FXCollections.observableArrayList();
				
				ListItem o = null;
				do
				{
					try
					{
						o = (ListItem) is.readObject();
						
						if (o!=null)
							l.add(o);
					}
					catch (EOFException e)
					{
						o = null;
					}
				} while (o!=null);
				
				is.close();
				return l;
			}
			else
			{
				Object o = is.readObject();
				is.close();
				return o;
			}
		} 
		catch (Exception e1) 
		{
			throw new RuntimeException(e1);
		}
	}
}
